package com.yc.cloud.admin.controller;


import com.yc.cloud.admin.dto.request.HwCameraCreateReqDTO;
import com.yc.cloud.admin.dto.request.HwCameraUpdateReqDTO;
import com.yc.cloud.admin.dto.request.HwCameraQueryReqDTO;
import com.yc.cloud.admin.dto.request.PtzControlReqDTO;
import com.yc.cloud.admin.dto.request.CameraStorageStrategyBindReqDTO;
import com.yc.cloud.common.basic.api.ResponseResult;
import com.yc.cloud.common.orm.CommonPage;
import com.yc.cloud.admin.vo.HwCameraVo;
import com.yc.cloud.admin.vo.HwCameraStorageRelationVo;
import com.yc.cloud.admin.vo.CameraBoundStorageStrategyVo;
import com.yc.cloud.admin.service.HwCameraService;
import com.yc.cloud.admin.service.SipServerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;

/**
 * <p>
 * 摄像头管理表 前端控制器
 * </p>
 *
 * @author kinggu
 * @since 2025-08-25
 */
@Slf4j
@RestController
@Api(tags = "摄像头管理表")
@RequestMapping("/hw-cameras")
public class HwCameraController {

    @Resource
    private HwCameraService hwCameraService;
    
    @Resource
    private SipServerService sipServerService;

    @ApiOperation("创建摄像头")
    @PostMapping
    public ResponseResult<HwCameraVo> create(@Validated @RequestBody HwCameraCreateReqDTO createReqDTO) {
        HwCameraVo newVo = hwCameraService.create(createReqDTO);
        if (newVo != null) {
            return ResponseResult.success(newVo);
        }
        return ResponseResult.failed("创建失败");
    }

    @ApiOperation("更新摄像头")
    @PutMapping("/{id}")
    public ResponseResult<HwCameraVo> update(@PathVariable("id") Long id, @Validated @RequestBody HwCameraUpdateReqDTO updateReqDTO) {
        updateReqDTO.setId(id);
        HwCameraVo updatedVo = hwCameraService.update(updateReqDTO);
        if (updatedVo != null) {
            return ResponseResult.success(updatedVo);
        }
        return ResponseResult.failed("更新失败");
    }

    @ApiOperation("删除摄像头")
    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> delete(@PathVariable("id") Long id) {
        boolean success = hwCameraService.delete(id);
        if (success) {
            return ResponseResult.success(true);
        }
        return ResponseResult.failed("删除失败");
    }

    @ApiOperation("获取摄像头详情")
    @GetMapping("/{id}")
    public ResponseResult<HwCameraVo> getById(@PathVariable("id") Long id) {
        return ResponseResult.success(hwCameraService.getVOById(id));
    }

    @ApiOperation("查询摄像头列表")
    @GetMapping
    public ResponseResult<CommonPage<HwCameraVo>> list(@Validated HwCameraQueryReqDTO queryReqDTO) {
        return ResponseResult.success(hwCameraService.list(queryReqDTO));
    }


    @ApiOperation("置顶摄像头")
    @PostMapping("/{id}/pin")
    public ResponseResult<Boolean> pin(@PathVariable("id") @ApiParam("摄像头ID") Long id) {
        boolean success = hwCameraService.pin(id);
        if (success) {
            return ResponseResult.success(true);
        }
        return ResponseResult.failed("置顶失败");
    }

    @ApiOperation("取消置顶摄像头")
    @PostMapping("/{id}/unpin")
    public ResponseResult<Boolean> unpin(@PathVariable("id") @ApiParam("摄像头ID") Long id) {
        boolean success = hwCameraService.unpin(id);
        if (success) {
            return ResponseResult.success(true);
        }
        return ResponseResult.failed("取消置顶失败");
    }

    @ApiOperation("获取未绑定设备的摄像头列表")
    @GetMapping("/unbound")
    public ResponseResult<List<HwCameraVo>> getUnboundCameras() {
        List<HwCameraVo> unboundCameras = hwCameraService.getUnboundCameras();
        return ResponseResult.success(unboundCameras);
    }

    @ApiOperation("PTZ摄像头控制")
    @PostMapping("/{id}/ptz")
    public ResponseResult<Boolean> controlPtz(
            @PathVariable("id") @ApiParam("摄像头ID") Long cameraId,
            @Validated @RequestBody PtzControlReqDTO ptzControlReq) {
        try {
            // 根据摄像头ID获取摄像头信息
            HwCameraVo cameraVo = hwCameraService.getVOById(cameraId);
            if (cameraVo == null) {
                return ResponseResult.failed("摄像头不存在");
            }
            
            // 检查是否有SIP用户名(设备ID)
            if (cameraVo.getSipUsername() == null || cameraVo.getSipUsername().trim().isEmpty()) {
                return ResponseResult.failed("摄像头未配置SIP设备ID，无法进行PTZ控制");
            }
            
            String deviceId = cameraVo.getSipUsername();
            
            log.info("PTZ控制请求: cameraId={}, deviceId={},channel={}, command={}, horizonSpeed={}, verticalSpeed={}, zoomSpeed={}", 
                    cameraId, deviceId,cameraVo.getVideoChannel(), ptzControlReq.getCommand(), ptzControlReq.getHorizonSpeed(), 
                    ptzControlReq.getVerticalSpeed(), ptzControlReq.getZoomSpeed());
            
            boolean success = sipServerService.controlPtz(deviceId,cameraVo.getVideoChannel(), ptzControlReq.getCommand(), 
                    ptzControlReq.getHorizonSpeed(), ptzControlReq.getVerticalSpeed(), ptzControlReq.getZoomSpeed());
            
            if (success) {
                return ResponseResult.success(true);
            } else {
                return ResponseResult.failed("PTZ控制失败");
            }
        } catch (Exception e) {
            log.error("PTZ控制异常: cameraId={}, command={}", cameraId, ptzControlReq.getCommand(), e);
            return ResponseResult.failed("PTZ控制异常");
        }
    }

    @ApiOperation("设置摄像头存储策略（支持绑定多个策略，传空数组则清除所有绑定）")
    @PostMapping("/{cameraId}/storage-strategies")
    public ResponseResult<Boolean> bindStorageStrategy(
            @PathVariable("cameraId") @ApiParam("摄像头ID") Long cameraId,
            @Validated @RequestBody CameraStorageStrategyBindReqDTO bindReqDTO) {
        boolean success = hwCameraService.bindStorageStrategy(cameraId, bindReqDTO);
        if (success) {
            return ResponseResult.success(true);
        }
        return ResponseResult.failed("批量绑定存储策略失败");
    }


    @ApiOperation("查询摄像头绑定的存储策略列表")
    @GetMapping("/{cameraId}/storage-strategies")
    public ResponseResult<List<CameraBoundStorageStrategyVo>> getStorageStrategies(
            @PathVariable("cameraId") @ApiParam("摄像头ID") Long cameraId) {
        List<CameraBoundStorageStrategyVo> strategies = hwCameraService.getCameraBoundStorageStrategies(cameraId);
        return ResponseResult.success(strategies);
    }
}

